package com.hw.protocol.tool.decode.hw;

import com.hw.protocol.tool.model.entity.hw.Alertor;
import com.hw.protocol.tool.model.entity.hw.AlertorData;
import com.hw.protocol.tool.util.CrcUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : lihy
 * @date : 2023/10/24 10:21
 * description: 商业报警器实时数据解码器
 */
@Slf4j
public class AlertorDecode {

    private Alertor alertor;

    ByteBuf dataBuf;

    public AlertorDecode(Alertor alertor, byte[] data) {
        this.alertor = alertor;
        this.dataBuf = Unpooled.wrappedBuffer(data);
    }

    public boolean buildObject(){
        if (crc()) {
            int crc = dataBuf.readShort();
            byte[] noCrc = new byte[dataBuf.capacity() - 2];
            dataBuf.getBytes(0, noCrc);
            int calCrc = CrcUtil.getCrcInteger(noCrc, true);
            if (crc != calCrc) {
                byte[] allBytes = new byte[dataBuf.capacity()];
                dataBuf.getBytes(0, allBytes);
                log.error("数据校验失败，原始数据:[{}]", allBytes);
                return false;
            }
        }
        alertor.setMeterType(dataBuf.readShortLE());
        AlertorData[] alerts = new AlertorData[8];
        for (int i = 0; i < 8; i++) {
            alerts[i].setSenser(dataBuf.readByte());
            alerts[i].setData(dataBuf.readFloatLE());
            alerts[i].setStatus(dataBuf.readByte());
        }
        alertor.setAlerts(alerts);

        byte[] flag = new byte[4];
        dataBuf.getBytes(dataBuf.capacity() - 4, flag);
        alertor.setFlag(flag);

        dataBuf.release();
        return true;
    }


    boolean crc() {
        return false;
    }
}
